<?php

namespace App\Repositories;

use App\Models\Coupon;
use App\Models\CouponMapping;

class CouponRepository
{
    public function getList($filter = null, int $pageSize = 10, int $pageNum = 1): array
    {
        $res = Coupon::query()
            ->from("coupon as c")
            ->leftJoin("coupon_mapping as cm", function ($join) use ($filter) {
                $join->on("cm.coupon_id", "=", "c.id")
                    ->where("cm.status", "=", 0)
                    ->where("cm.uid", "=", intval($filter['uid']));
            })
            ->when(isset($filter['shop_id']), function ($q) use ($filter) {
                return $q->where("c.shop_id", "=", intval($filter['shop_id']));
            })
//            ->where("c.create_user_id", "=", intval($filter["coupon_create_user_id"]))
            ->where(['c.status' => 1])
            ->orderBy('cm.id', 'desc')
            ->paginate($pageSize, "c.*", null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => &$v) {
            $v['dead_time'] = date("Y-m-d H:i:s", $v['dead_time']);

            $mapping = CouponMapping::query()->where([
                'uid' => $filter['uid'],
                'coupon_id' => $v['id']
            ])
                ->first();
            if (empty($mapping))
                continue;

            if ($mapping['dead_time'] < time() && $mapping['status'] == 0) {
                CouponMapping::query()->where(['id' => $mapping['id']])
                    ->update(['status' => 2]);
                $mapping['status'] = 2;
            }
            $v['mapping'] = $mapping;
        }
        return $res;
    }


    /**
     * 领取优惠券列表
     * @param null $filter
     * @param int $pageSize
     * @param int $pageNum
     * @return array
     */
    public function getMappingList($filter = null, int $pageSize = 10, int $pageNum = 1)
    {
        $res = Coupon::query()
            ->from("coupon as c")
            ->join("coupon_mapping as cm", "cm.coupon_id", "=", "c.id")
            ->when(isset($filter['shop_id']), function ($q) use ($filter) {
                return $q->where("c.shop_id", "=", intval($filter['shop_id']));
            })
            ->where([
                'cm.status' => intval($filter['status']),
                'cm.uid' => intval($filter['uid'])
            ])
            ->orderBy('cm.id', 'desc')
            ->paginate($pageSize, ["c.*", 'cm.dead_time', 'cm.status as mapping_status'], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => &$v) {
            if (date("Y-m-d", $v['dead_time']) == date("Y-m-d")) {
                $v['is_today'] = 1;
            }
            $v['dead_time'] = date("Y-m-d H:i:s", $v['dead_time']);
            $v['type_title'] = coupon_type($v['type']);

            if ($v['dead_time'] < time() && $v['mapping_status'] == 0) {
                CouponMapping::query()->where(['id' => $v['id']])
                    ->update(['status' => 2]);
                $v['mapping_status'] = 2;
            }
        }
        return $res;
    }

    public function getMapping($coupon_id = 0, $uid = 0)
    {
        if (!$coupon_id || !$uid)
            return null;

        $coupon = $this->getOne($coupon_id);
        if (empty($coupon))
            return null;

        $mapping = CouponMapping::query()->where([
            'uid' => $uid,
            'coupon_id' => $coupon_id
        ])->first();

        if ($mapping && $mapping['dead_time'] < time() && $mapping['status'] == 0) {
            CouponMapping::query()->where(['id' => $mapping['id']])
                ->update(['stautus' => 2]);
            $mapping['status'] = 2;
        }

        return compact('coupon', 'mapping');
    }

    public function getOne($id = 0)
    {
        $res = Coupon::query()->where(['id' => $id])->first();

        if (!isset($res))
            return null;

        return $res;
    }

    public function getMappingById($mappingId = 0)
    {
        $res = CouponMapping::query()->where(['id' => $mappingId])->first();
        if (!isset($res))
            return null;

        $res['coupon'] = $this->getOne($res['coupon_id']);

        return $res;
    }

    public function gainMapping($coupon_id = 0, $uid = 0)
    {

        if (!$coupon_id || !$uid)
            return retFail("参数错误");

        $coupon = $this->getOne($coupon_id);
        if (empty($coupon) || $coupon['status'] !== 1) {
            return retFail("优惠券不存在或已失效");
        }

        $mapping = CouponMapping::query()->where([
            'uid' => $uid,
            'coupon_id' => $coupon_id
        ])->first();

        if (!isset($mapping)) {
            $mapping = CouponMapping::query()->create([
                'uid' => $uid,
                'coupon_id' => $coupon_id,
                'dead_time' => strtotime("+" . $coupon['times'] . " days"),
                'status' => 0
            ]);
        }

        return retSuc($mapping);
    }

    /**
     * 获取可用优惠券
     * @param int $uid
     * @param int $price
     */
    public function getCanUseCoupon($uid = 0, $price = 0, $type = 1)
    {
        $res = CouponMapping::from("coupon_mapping as cm")
            ->join("coupon as c", "c.id", "=", 'cm.coupon_id')
            ->where([
                'cm.uid' => $uid,
                'cm.status' => 0,
                'c.status' => 1,
                'c.type' => $type,
            ])
            ->where("cm.dead_time", ">=", time())
            ->when($price > 0, function ($q) use ($price) {
                return $q->where("c.min_price", "<=", $price);
            })
            ->orderBy("c.min_price", 'desc')
            ->orderBy("c.price", 'desc')
            ->orderBy("dead_time", "asc")
            ->get(['cm.id', 'cm.coupon_id', 'c.price', 'c.combo_id', 'cm.dead_time', 'c.min_price', 'c.summary']);

        foreach ($res as $k => &$v) {
            if ($v['dead_time'] > 0) {
                $v['dead_time'] = date("m-d", $v['dead_time']);
                $v['dead_time'] = $v['dead_time'] == date("m-d") ? '今日到期' : '有效期至' . $v['dead_time'];
            }
        }

        if (UID == 2) {
//            dd($res);
        }

        if ($price > 0) {
            return $res[0];
        } else {
            return $res;
        }

    }

}
